package edu.biwu.dao.impl;

import edu.biwu.dao.ProductDao;
import edu.biwu.po.Product;
import edu.biwu.utils.ConnectionFactory;
import lombok.Setter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;
@Setter
@Repository
public class ProductDaoImpl implements ProductDao {
    //通过setter方法在spring中注入QueryRunner对象
    @Autowired
    private QueryRunner queryRunner;

    @Autowired
    private ConnectionFactory connectionFactory;

//   例如: public QueryRunner getQueryRunner() {
//        return queryRunner;
//    }

    //增删改绑定当前线程的连接 方便事务的管理
    @Override
    public List<Product> findAll() {
        try {
            return queryRunner.query(connectionFactory.currentThreadConnection(),"SELECT * FROM spring.product",new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteProduct(int pid) {
        try {
            queryRunner.update(connectionFactory.currentThreadConnection(), "DELETE FROM spring.product WHERE pid = ?", pid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConnection(),"INSERT INTO sping.product SET pname=?,price=?,category=?",
                    product.getPname(),product.getPrice(),product.getCategory());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConnection(),"UPDATE spring.product SET pname=?,price=?,category=? " +
                            "WHERE pid=?", product.getPname(),
                    product.getPrice(), product.getCategory(), product.getPid());
//            int i = 1/0; //测试事务回滚
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
